from flask import abort
from flask import current_app
from flask import g, jsonify
from flask import request
from flask import session
from info import db,constants
from info.models import User, Category, News
from info.utlis.response_code import RET
from . import profile_bp
from flask import render_template
from info.utlis.common import login_user_data
from info.utlis.image_store import qiniu_image_store

# 展示偶像用户发布过的新闻
@profile_bp.route("/other_news_list")
def other_news_list():
    """用户发布的新闻列表展示"""
    # 1.获取参数
    # 前端HTML的页数在JS的get请求中写，get请求用args参数接收
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    # 2.参数校验
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 3.逻辑处理
    # lazy="dynamic"如果真正用到里面的值，就会给你返回一个列表数据，如果只是简单的查询就会返回一个查询对象给你
    news_list = []
    current_page = 1
    total_page = 1
    # news1 = News.query.filter(News.user_id == user.id)
    # print(news1)
    if user_id:
        try:
            paginate = News.query.filter(News.user_id == user_id). \
                paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
            news_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)

    # 新闻对象列表转成字典列表

    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    # 4.返回值
    return jsonify(errno=RET.OK,errmsg="OK",data=data)


# 进入偶像界面可以进行取关和重新关注操作
@profile_bp.route('/other_info')
@login_user_data
def other_info():
    user_id = request.args.get("user_id")
    user = g.user
    if not user_id:
        abort(404)

    if not user:
        abort(404)
    other = None #type:User
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    is_followed = False
    if other:
        if other in user.followed:
            is_followed = True
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }

    # 4.返回值
    return render_template("news/other.html", data=data)


# 用户关注列表展示
@profile_bp.route("/user_follow")
@login_user_data
def user_follow():
    # 1.获取参数
    # 第一次进入该页面没有传p参数，默认为第一页
    p = request.args.get("p", 1)
    user = g.user
    # 2.参数校验
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 3.逻辑处理
    # lazy="dynamic"如果真正用到里面的值，就会给你返回一个列表数据，如果只是简单的查询就会返回一个查询对象给你
    news_list = []
    current_page = 1
    total_page = 1
    # news1 = News.query.filter(News.user_id == user.id)
    # print(news1)
    if user:
        try:
            paginate = user.followed.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
            followed_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)

    # 新闻对象列表转成字典列表

    followed_dict_list = []
    for followed in followed_list if followed_list else []:
        followed_dict_list.append(followed.to_dict())

    data = {
        "users": followed_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    # 4.返回值
    return render_template("news/user_follow.html", data=data)


# 用户发布过的新闻列表
@profile_bp.route("/news_list")
@login_user_data
def news_list():
    """用户发布的新闻列表展示"""
    #1.获取参数
    p = request.args.get("p", 1)
    user = g.user
    # 2.参数校验
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 3.逻辑处理
    # lazy="dynamic"如果真正用到里面的值，就会给你返回一个列表数据，如果只是简单的查询就会返回一个查询对象给你
    news_list = []
    current_page = 1
    total_page = 1
    # news1 = News.query.filter(News.user_id == user.id)
    # print(news1)
    if user:
        try:
            paginate = News.query.filter(News.user_id == user.id).\
                paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
            news_list = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)

    # 新闻对象列表转成字典列表

    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_review_dict())

    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    # 4.返回值
    return render_template("news/user_news_list.html", data=data)

# 用户去发布新闻内容
@profile_bp.route("/news_release",methods=['post','get'])
@login_user_data
def news_release():
    if request.method == "GET":
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        category_dict_list = []
        for category in categories if categories else []:
            category_dict_list.append(category.to_dict())
        category_dict_list.pop(0)
        data = {
            "categories":category_dict_list
        }
        return render_template("news/user_news_release.html",data=data)

    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    source = "个人发布"
    user = g.user
    # 判空
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")

    # 逻辑处理
    image_data = index_image.read()
    try:
        image_name = qiniu_image_store(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传图片到七牛云失败")

    image_url = constants.QINIU_DOMIN_PREFIX + image_name

    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = image_url
    news.content = content
    news.source = source
    news.user_id = user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="上交新闻数据异常")

    return jsonify(errno=RET.OK,errmsg="上传成功")

# 用户收藏新闻列表
#  /user/collection?p=1
@profile_bp.route("/collection")
@login_user_data
def user_collection():
    # 一页展示多少条数据
    p = request.args.get("p",1)
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    news_list = []
    current_page = 1
    total_page = 1
    if user:
        try:
            paginate = user.collection_news.paginate(p,constants.USER_COLLECTION_MAX_NEWS,False)
            items = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
    news_dict_list = []
    for item in items if items else []:
        news_dict_list.append(item.to_review_dict())
    data = {
        "collections":news_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return render_template('news/user_collection.html',data=data)

# 用户修改密码
@profile_bp.route('/pass_info',methods=['post','get'])
@login_user_data
def pass_info():
    if request.method == "GET":
        return render_template('news/user_pass_info.html')

    params_dict = request.json
    old_password = params_dict.get("old_password")
    new_password = params_dict.get("new_password")
    user = g.user
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    if not user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")
    # 判断旧密码是否填写正确
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR,errmsg="旧密码填写错误")
    if old_password == new_password:
        return jsonify(errno=RET.PARAMERR,errmsg="旧密码不能和新密码相同")
    # 修改旧密码
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存用户对象异常")
        # 4.返回值
    return jsonify(errno=RET.OK, errmsg="修改密码成功")

#用户上传头像
@profile_bp.route('/pic_info',methods=['post','get'])
@login_user_data
def pic_info():
    if request.method == "GET":
        return render_template("news/user_pic_info.html")

    # POST获取用户上传的图片二进制数据
    avatar_data = request.files.get("avatar").read()
    user = g.user

    # 校验参数
    if not avatar_data:
        return jsonify(errno=RET.NODATA, errmsg="图片数据不能为空")
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 逻辑处理
    try:
        #  调用封装好的方法将图片上传到七牛云
        image_name = qiniu_image_store(avatar_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传图片到七牛云失败")
    # 只将图片名称存储，防止后期修改七牛云域名
    user.avatar_url = image_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存用户url失败")

    full_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        "avtual_url":full_url
    }
    return jsonify(errno=RET.OK,errmsg="上传图片到七牛云成功",data=data)

# 用户基本信息
@profile_bp.route('/base_info',methods=['post','get'])
@login_user_data
def base_info():
# POST请求主要更改用户数据库数据和session值
    user = g.user
    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template('news/user_base_info.html' ,data=data)
    # POST请求 修改用户基本资料
    # 1.获取参数
    params_dict = request.json
    nick_name = params_dict.get("nick_name")
    signature = params_dict.get("signature")
    gender = params_dict.get("gender")

    #  2.1 非空判断
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")

    # 2.2 用户是否登录判断
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    if gender not in ["MAN", "WOMAN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="action数据填写错误")

    # 3.逻辑处理
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    # 更新session中的nick_name数据
    session["nick_name"] = nick_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="修改用户数据异常")

        # 4.返回值处理
    return jsonify(errno=RET.OK, errmsg="修改用户数据成功")

# 用户右上角用户头像
@profile_bp.route('/info')
@login_user_data
def user_info():

    user = g.user
    data = {
        "user_info": user.to_dict() if user else None,
    }
    return render_template('news/user.html',data=data)